<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item
          v-for="(item, index) in breadList"
          :key="index"
          :to="{ path: item.path }"
        >
          {{ item.meta.title }}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-select
          v-model="query.type"
          placeholder="用户类型"
          class="handle-select mr10"
        >
          <el-option key="3" label="全部" value=""></el-option>
          <el-option key="0" label="管理员" value="0"></el-option>
          <el-option key="1" label="普通用户" value="1"></el-option>
          <el-option key="2" label="VIP用户" value="2"></el-option>
        </el-select>
        <el-input
          v-model="query.userName"
          placeholder="请输入用户名"
          class="handle-input mr10"
        ></el-input>
        <el-button type="primary" :icon="Search" @click="handleSearch"
          >搜索</el-button
        >
      </div>
      <el-table
        :data="tableData"
        border
        stripe
        size="large"
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
      >
        <el-table-column
          prop="userId"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户头像"
          width="150"
          align="center"
          prop="u_img"
        >
          <template #default="scope">
            <img :src="`${IMG_URL}${scope.row.u_img}`" width="80" height="80" />
          </template>
        </el-table-column>
        <el-table-column
          prop="userName"
          label="用户名"
          width="80"
          align="center"
        ></el-table-column>
        <el-table-column label="用户类型" width="110" align="center">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.type == '0'
                  ? 'danger'
                  : scope.row.type == '1'
                  ? 'success'
                  : 'warning'
              "
            >
              {{
                scope.row.type == "0"
                  ? "管理员"
                  : scope.row.type == "1"
                  ? "普通用户"
                  : "VIP用户"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 性别 -->
        <el-table-column label="性别" align="center" width="70">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.sex == '1'
                  ? '' // ? 'brand'
                  : scope.row.sex == '0'
                  ? 'warning'
                  : ''
              "
            >
              {{
                scope.row.sex == "1"
                  ? "男"
                  : scope.row.sex == "0"
                  ? "女"
                  : "未知"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 地址 -->
        <el-table-column
          prop="address"
          label="地址"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="130"
          align="center"
        ></el-table-column>
        <!-- 状态 -->
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status == '1'
                  ? 'success'
                  : scope.row.status == '0'
                  ? 'danger'
                  : ''
              "
            >
              {{
                scope.row.status == "1"
                  ? "正常"
                  : scope.row.status == "0"
                  ? "停用"
                  : "未知"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column label="注册时间" width="180" align="center">
          <template #default="scope">
            {{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm") }}
          </template>
        </el-table-column> -->
        <el-table-column
          prop="createdAt"
          label="注册时间"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              :icon="EditPen"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >

            <el-popconfirm
              title="确定要删除此用户"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-if="totalCount"
          v-model:currentPage="query.currentPage"
          v-model:page-size="query.pageSize"
          layout="prev, pager, next, jumper"
          :total="totalCount"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="centerDialogVisible"
      title="用户编辑"
      width="35%"
      :before-close="cancel"
    >
      <div>
        <el-scrollbar height="50vh">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="100px"
            status-icon
          >
            <el-form-item label="用户头像" prop="u_img">
              <el-upload
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :on-remove="handledel"
                :on-change="changeUploadImg"
                ref="upload"
                :file-list="fileList"
                :multiple="true"
                name="file"
                v-model="fileList"
                :limit="1"
                :class="{ hidden: fileList.length == 1 }"
              >
                <el-icon>
                  <Plus />
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon>
                          <ZoomIn />
                        </el-icon>
                      </span>
                      <span
                        v-if="!disabled"
                        class="el-upload-list__item-delete"
                        @click="handledel(file)"
                      >
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
                <template #tip>
                  <div class="el-upload__tip">
                    只能上传 .jpg 或 .png 格式图片，且图片大小不能超过256KB！
                  </div>
                </template>
              </el-upload>
              <!--  放大的图片  -->
              <el-dialog v-model="dialogVisible" top="7vh">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="width: 100%; height: auto"
                />
              </el-dialog>
            </el-form-item>
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="ruleForm.userName" @input="checkuserName" />
            </el-form-item>
            <el-form-item label="用户电话" prop="phone">
              <el-input v-model="ruleForm.phone" />
            </el-form-item>
            <el-form-item label="用户地址" prop="address">
              <el-input v-model="ruleForm.address" />
            </el-form-item>
            <el-form-item label="用户性别" prop="sex">
              <el-radio-group v-model="ruleForm.sex">
                <el-radio label="0">女</el-radio>
                <el-radio label="1">男</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户类型" prop="type">
              <el-radio-group v-model="ruleForm.type">
                <el-radio label="0">管理员</el-radio>
                <el-radio label="1">普通用户</el-radio>
                <el-radio label="2">vip用户</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-radio-group v-model="ruleForm.status">
                <el-radio label="0">停用</el-radio>
                <el-radio label="1">正常</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >更新</el-button
          >
          <!-- <el-button @click="resetForm(ruleFormRef)">重置表单</el-button> -->
          <el-button @click="cancel">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, watch } from "vue";
import request from "../../utils/request";
import { ElNotification, ElMessage } from "element-plus";
import { EditPen, Search } from "@element-plus/icons-vue";
// import moment from "moment";
import { IMG_URL } from "@/utils/imgStatic";

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const disabled = ref(false);
const fileList = ref([]);
const upload = ref(null);

// 移除图片
const handledel = (file) => {
  fileList.value = [];
};
//展示大图
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

//限制大小
//文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const changeUploadImg = (file) => {
  const isJPG = file.raw.type === "image/jpeg";
  const isPNG = file.raw.type === "image/png";
  if (!isJPG && !isPNG) {
    ElMessage.error("上传图片只能是 JPG 或者 PNG 格式！");
    // 取消时在文件列表中删除该文件
    upload.value.handleRemove(file);
    return isJPG || isPNG;
  } else if (file.size / 1024 > 256) {
    ElMessage.error("图片大小不能超过256KB！");
    upload.value.handleRemove(file);
    return false;
  } else {
    console.log(file);
    // file.raw.name = new Date().getTime();
    fileList.value.push(file);
    rules.u_img = [];
  }
};

let breadList = []; // 路由集合
const route = useRoute();
const getBreadcrumb = (url) => {
  let matched = url.matched;
  //如果不是首页
  if ("Home" == matched[0].name) {
    matched[0].meta = { title: "系统首页" };
  }
  breadList = matched;
};
watch(
  route,
  (newValue, oldValue) => {
    // console.log(222222,newValue)
    getBreadcrumb(newValue);
  },
  { deep: true, immediate: true }
);
//重置表单
// const resetForm = (formEl) => {
//   if (!formEl) return;
//   formEl.resetFields();
// };

//取消表单
const cancel = () => {
  centerDialogVisible.value = false;
  fileList.value = [];
};

const ruleForm = reactive({
  userId: "",
  userName: "",
  // password: "",
  address: "",
  phone: "",
  type: 0,
  status: 1,
  sex: 1,
  u_img: "",
});
const rules = reactive({
  userName: [
    {
      required: true,
      message: "请输入用户名",
      trigger: ["blur", "change"],
    },
    {
      pattern: /^\S*$/, // 正则表达式校验用户名，不允许空格
      message: "用户名中不能有空格",
      trigger: ["blur", "change"],
    },
    // {
    //   pattern: /^[a-zA-Z0-9_]+$/, // 正则表达式校验用户名，只允许字母、数字和下划线
    //   message: "用户名只能包含字母、数字和下划线",
    //   trigger: ["blur", "change"],
    // },
  ],
  phone: [
    {
      required: true,
      message: "请输入电话号码",
      trigger: ["blur", "change"],
    },
    {
      pattern: /^1[3-9]\d{9}$/, // 正则表达式校验手机号
      message: "手机号格式不正确",
      trigger: ["blur", "change"],
    },
  ],
  address: [
    {
      required: false,
      message: "请输入地址",
      trigger: "blur",
    },
  ],
  type: [
    {
      required: true,
      message: "请选择用户类型",
      trigger: "change",
    },
  ],
  status: [
    {
      required: true,
      message: "请选择用户状态",
      trigger: "change",
    },
  ],
  sex: [
    {
      required: true,
      message: "请选择用户性别",
      trigger: "change",
    },
  ],
  u_img: [
    {
      required: true,
      message: "请上传用户头像",
      trigger: "change",
    },
  ],
});
const ruleFormRef = ref();
const centerDialogVisible = ref(false);
const query = reactive({
  address: "",
  userName: "",
  currentPage: 1,
  pageSize: 5,
});
const tableData = ref([]);
const totalCount = ref(0);
// 获取表格数据
const getData = () => {
  request
    .request({
      url: "/user/getAllUsersByPage",
      params: {
        type: query.type,
        userName: query.userName,
        currentPage: query.currentPage,
        pageSize: query.pageSize,
      },
      method: "get",
    })
    .then((res) => {
      //获取当前页的数据
      tableData.value = res.data.data.rows;
      //获取总记录数
      totalCount.value = res.data.data.count;
    })
    .catch((e) => {
      console.log(e);
    });
};
getData();
// 查询操作
const handleSearch = () => {
  query.currentPage = 1;
  getData();
};
// 分页导航
const handleCurrentChange = (val) => {
  query.currentPage = val;
  getData();
  // console.log(val);
};
// 删除操作
const handleDelete = (index, row) => {
  console.log(row);
  request
    .request({
      url: "/user/delete",
      method: "post",
      data: { userId: row.userId },
    })
    .then((res) => {
      if (res.data.code === "200") {
        ElMessage({
          message: "用户信息删除成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: "删除失败，请重试",
          type: "error",
        });
      }
      getData();
    });
};
const handleEdit = (index, row) => {
  centerDialogVisible.value = true;
  ruleForm.userId = row.userId;
  ruleForm.userName = row.userName;
  // ruleForm.password = row.password;
  ruleForm.address = row.address;
  ruleForm.phone = row.phone;
  ruleForm.sex = row.sex;
  ruleForm.type = row.type;
  ruleForm.status = row.status;
  ruleForm.u_img = row.u_img;
  fileList.value.push({
    url: `${IMG_URL}${row.u_img}`,
  });
  console.log(ruleForm);
};
const checkuserName = async () => {};

const submitForm = async (formEl) => {
  const type = ref(false);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    const formData = new FormData();
    fileList.value.forEach((value, index) => {
      formData.append("file", value.raw);
      if (value.hasOwnProperty("raw") && value.hasOwnProperty("name")) {
        ruleForm.u_img = value.raw.name;
        type.value = true;
      }
    });
    fileList.value = [];
    formData.append("userId ", ruleForm.userId);
    formData.append("userName", ruleForm.userName);
    // formData.append("password", ruleForm.password);
    formData.append("address", ruleForm.address);
    formData.append("phone", ruleForm.phone);
    formData.append("type", ruleForm.type);
    formData.append("status", ruleForm.status);
    formData.append("sex", ruleForm.sex);
    formData.append("u_img", ruleForm.u_img);
    if (valid) {
      console.log("提交更新", fields);
      //发送ajax请求
      request
        .request({
          url: "/user/update",
          method: "post",
          data: ruleForm,
        })
        .then((res) => {
          if (res.data.code === "200") {
            ElMessage({
              message: "用户信息更新成功",
              type: "success",
            });
            centerDialogVisible.value = false;
            getData();
          } else {
            ElMessage({
              message: "更新失败，请重试",
              type: "error",
            });
          }
        })
        .catch((error) => {
          ElMessage({
            message: "请求错误，请重试",
            type: "error",
          });
          console.error(error);
        });
      if (type.value)
        request.request({
          url: "/user/upload",
          method: "post",
          data: formData,
        });
    } else {
      ElNotification({
        title: "校验失败",
        message: "请重新填写信息",
        type: "error",
      });
    }
  });
};
</script>

<style>
.hidden .el-upload--picture-card {
  display: none;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 200px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
